#include "../DataLib/MoveMouse.h"
#include "Server.h"
#include <iostream>

using namespace std;

int main(void)
{
	WSADATA data;
	try
	{
		int size;
		ICommand* cmd;
		pSocket::InitWinSock(data);
		Server server("0.0.0.0", 8080);
		cout << "Setting up server..." << endl;
		server.StartListening();
		cout << "Listening..." << endl;
		while(true)
		{
			cout << "Waiting for a client..." << endl;
			server.WaitForClient();
			cout << "Waiting for commands..." << endl;
			try
			{
				while(1)
				{
					size = server.ReceiveBytes();
					if(size)
					{	
						Command h(server.GetBuffer());
						cout << "Data received" << endl;
						cout << "Rebuilding packet" << endl;
						if(cmd = ICommand::GetCommand(h))
						{
							cout << "Command received. Executing." << endl;
							cmd->Do();
						}
					}
				}
			}
			catch(int error)
			{
				if(error == SOCKET_ERROR)
				{
					cout << "Client disconnected." << endl;
				}
				else
				{
					cout << "Something bad happened: " << error << endl;
				}
			}
		}
		pSocket::CleanWinSock();
	}
	catch(...)
	{
	}
	system("pause");
	return 0;
}
